﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ResourceEditor.Core.ResourceDataObjects
{
    public class ResourceDataFile : ResourceData<byte[]>, ISupportFileResource
    {
        #region Ctor
        public ResourceDataFile(ResourceFile container)
            : base(container)
        {

        }
        #endregion

        #region IFileObject Members

        public void Add(string fileName)
        {
            try
            {
                FileInfo info = new FileInfo(fileName);
                byte[] buffer = null;

                using (FileStream reader = new FileStream(fileName, FileMode.Open))
                {
                    buffer = new byte[reader.Length];
                    reader.Read(buffer, 0, buffer.Length);
                }
                Add(info.Name, buffer);
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
                throw;
            }
        }

        public void ChangeItem(string key, string fileName)
        {
            try
            {
                byte[] buffer = null;

                using (FileStream reader = new FileStream(fileName, FileMode.Open))
                {
                    buffer = new byte[reader.Length];
                    reader.Read(buffer, 0, buffer.Length);
                }
                ChangeItem(key, buffer);
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
                throw;
            }
        }

        public string GetExtension(string key)
        {
            throw new NotImplementedException();
        }

        public void Export(string key, string fileName)
        {
            try
            {
                byte[] array = this[key].Current;
                using (FileStream fs = File.OpenWrite(fileName))
                {
                    fs.Write(array, 0, array.Length);
                }
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
                throw;
            }
        }

        #endregion
    }
}
